import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import { Route } from '@/models/connect';
import moment from 'moment';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

export const isAntDesignPro = (): boolean => {
  if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
    return true;
  }
  return window.location.hostname === 'preview.pro.ant.design';
};

// 给官方演示站点用，用于关闭真实开发环境不需要使用的特性
export const isAntDesignProOrDev = (): boolean => {
  const { NODE_ENV } = process.env;
  if (NODE_ENV === 'development') {
    return true;
  }
  return isAntDesignPro();
};

export const getPageQuery = () => parse(window.location.href.split('?')[1]);

/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */
export const getAuthorityFromRouter = <T extends Route>(
  router: T[] = [],
  pathname: string,
): T | undefined => {
  const authority = router.find(
    ({ routes, path = '/' }) =>
      (path && pathRegexp(path).exec(pathname)) ||
      (routes && getAuthorityFromRouter(routes, pathname)),
  );
  if (authority) return authority;
  return undefined;
};

export const getRouteAuthority = (path: string, routeData: Route[]) => {
  let authorities: string[] | string | undefined;
  routeData.forEach(route => {
    // match prefix
    if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
      if (route.authority) {
        authorities = route.authority;
      }
      // exact match
      if (route.path === path) {
        authorities = route.authority || authorities;
      }
      // get children authority recursively
      if (route.routes) {
        authorities = getRouteAuthority(path, route.routes) || authorities;
      }
    }
  });
  return authorities;
};

/**
 * 根据select option生成相应的map
 * @param option 下拉对象
 */
interface selectOption {
  key: string | number;
  text: string;
}
interface selectFn extends selectOption {
  map: (a: any, b?: any) => {};
  unshift: (item: selectOption) => {};
}

interface selectOptionAuthor {
  id: string | number;
  nickname: string;
}
interface selectFnAuthor extends selectOptionAuthor {
  map: (a: any, b?: any) => {};
  unshift: (item: selectOption) => {};
}
/**
 *
 * @param option
 * select对象转map
 */
export const selectEnum = (option: selectFn[] = []) => {
  // console.log('option',option)
  const opMap = { '': '全部' };
  if (option.length < 0) return {};
  option.map(item => {
    if (item.text) {
      opMap[item.key] = item.text;
    } else if (item.name) {
      opMap[item.key] = item.name;
    }

    return true;
  });
  return opMap;
};

//交易对专用
export const selectEnumMarket = (option: selectFn[] = []) => {
  console.log('option',option)
  const opMap = { '': '全部' };
  if (option.length < 0) return {};
  option.map(item => {
    if (item.name) {
      opMap[item.name] = item.name;
    } else if (item.key) {
      opMap[item.text] = item.text;
    }

    return true;
  });
  return opMap;
};

//house项目文章作者专用
export const selectEnumAuthor = (option: selectFnAuthor[] = []) => {
  console.log('option',option)
  const opMap = { '': '全部' };
  if (option.length < 0) return {};
  option.map(item => {
    if (item.id) {
      opMap[item.id] = item.nickname;
    }

    return true;
  });
  return opMap;
};

//winnie咨询人关系
export const selectRelationShip = (option: selectFnAuthor[] = []) => {
  console.log('option',option)
  const opMap = { '': '全部' };
  if (option.length < 0) return {};
  option.map(item => {
    if (item.id) {
      opMap[item.id] = item.name;
    }

    return true;
  });
  return opMap;
};

export const selectPrizeEnum = (option: selectFn[] = []) => {
  const opMap = { '': '全部' };
  if (option.length < 0) return {};
  option.map(item => {
    if (item.text) {
      opMap[item.key] = `${item.key}  ${item.text} `;
    } else if (item.name) {
      opMap[item.key] = item.name;
    }

    return true;
  });
  return opMap;
};

//开心岛门店
export const selectShopEnum = (option: selectFn[] = []) => {
  // console.log('option',option)
  const opMap = { '': '全部' };
  if (option.length < 0) return {};
  option.map((item:any) => {
    if (item.text) {
      opMap[item.id] = item.text;
    } else if (item.name) {
      opMap[item.id] = item.name;
    }

    return true;
  });
  return opMap;
};

/**
 * @param filters:[]
 * 去除columns中带有valueEnum属性的filters功能
 */
export const formatColumnsFilter = (columns: any[]) => {
  const newCol: any[] = [];
  columns.map(item => {
    if (item.valueEnum) {
      newCol.push({ ...item, filters: [] });
    } else {
      newCol.push(item);
    }
    return true;
  });
  return newCol;
};
/**
 * key text格式转label value格式：用于单选按钮组及复选按钮组中
 */
export const selectToLabel = (options: any) => {
  if (options && options.length > 0) {
    return options.map((item: { text: any; key: any }) => ({
      label: item.text,
      value: item.key,
    }));
  }
  return [];
};
/**
 * 格式化区间日期参数
 * params: 请求参数
 * dataName: 非必传，默认参数名为：
 * name: 原区间字段名称
*  {
      begin: 'begin_at',
      end: 'end_at',
      name:"range",
    }
 * 注：使用时把区间字段名称统一定义为range
 */
export const formatDataRange = (params: any, paramsDateName = {}) => {
  const newDateName = Object.assign(
    {
      begin: 'begin_at',
      end: 'end_at',
      name: 'range',
    },
    paramsDateName,
  );
  const range = params[newDateName.name] || [];
  let newParams = params;
  // 格式化参数
  if (range.length) {
    newParams = Object.assign({}, params, {
      [newDateName.begin]: range ? moment(range[0]).format('YYYY-MM-DD') : null,
      [newDateName.end]: range ? moment(range[1]).format('YYYY-MM-DD') : null,
    });
    // newDateName.name不是：begin_at 及 end_at才删除
    if (['begin_at', 'end_at'].indexOf(newDateName.name) === -1) {
      delete newParams[newDateName.name];
    }
  }
  return newParams;
};
/**
 * showButtons功能
 * 从common对象中获取showButtons对象并更返回
 * status: 默认不需要返回status，如需要返回, status值为true
 */
export const formatBtn = (options: any[], status = false) => {
  const obj = {};
  if (options && options.length > 0) {
    options.map(item => {
      // 按钮对象：不需要status，只需要判断按钮与区域的显示与隐藏的情况
      obj[item.key] = item.show;
      // 按钮对象：需要status状态时的情况
      if (status) {
        obj[item.key] = {
          show: item.show,
          status: item.status,
        };
      }
      return true;
    });
  }
  return obj;
};
